package com.ruoyi.system.test;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.system.domain.AttendanceRecords;
import com.ruoyi.system.mapper.AttendanceRecordsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("clean")
public class DatabaseCleanupTask {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseCleanupTask.class);

    @Autowired
    private AttendanceRecordsMapper attendanceRecordsMapper;

    // 每天下午两点执行任务
    @Scheduled(cron = "0 0 14 * * ?")
    public void cleanUpOldRecords() {
        try {
            // 获取超过两个月的记录
            List<AttendanceRecords> oldestRecords = attendanceRecordsMapper.getOldestRecords();
            if (!oldestRecords.isEmpty()) {
                // 提取记录的id，组成Long类型的数组
                List<Long> idList = new ArrayList<>();
                for (AttendanceRecords record : oldestRecords) {
                    idList.add(record.getId());
                }
                Long[] ids = idList.toArray(new Long[0]);
                // 执行删除操作
                int deleteCount = attendanceRecordsMapper.deleteAttendanceRecordsByIds(ids);
                String logMessage = "删除了" + deleteCount + "条超过两个月的旧记录";
                logger.info(logMessage);
                // 使用若依的日志工具记录
                LogUtils.info(logMessage);
            } else {
                String logMessage = "没有超过两个月的旧记录需要删除。";
                logger.info(logMessage);
                // 使用若依的日志工具记录
                LogUtils.info(logMessage);
            }
        } catch (Exception e) {
            String logMessage = "执行定时任务时出错: " + e.getMessage();
            logger.error(logMessage, e);
            // 使用若依的日志工具记录错误
            LogUtils.error(logMessage);
        }
    }
}